package com.fingard.dsp.bank.directbank.klb01;


import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.net.ConnState;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;


public class KLB01BatPayRec extends KLB01Base implements IBatPayRec{


	/* 批量代付提交 */
	@Override
	public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
		// TODO Auto-generated method stub
		RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_req1988.reqHeader);
		try {

			bnkVersion = "0.0.0.1";
        	bank ="KLB";
        	bnkOrgId=bankFront.corpNo;
        	bnkoOrgName=bankFront.org;
        	bnkTxCode="3030";
        	bnkTxPackNo=p_req1988.reqBatchNO;
        	
            XmlTextWriter xmlWriter = new XmlTextWriter();// 发银行报文的XML对象
            // 写入KLB01通用的头部节点
          
            writeCommonHeader(xmlWriter);
            
            xmlWriter.writeStartElement("body");
            
            
            xmlWriter.writeElementString("PayAccNo", p_req1988.ownAct);//PayAccNo	发起方账号		
            xmlWriter.writeElementString("TotalNum", p_req1988.totalNum);//TotalNum	交易笔数				为1，默认1
            xmlWriter.writeElementString("CurrType", "01");//CurrType	币种			01-人民币  ********	
            xmlWriter.writeElementString("TotalAmt", p_req1988.totalAmt);//TotalAmt	汇总代发金额			
            xmlWriter.writeElementString("TrnFlag", "7");//TrnFlag	处理标志			代发-7；代扣-8；
            xmlWriter.writeElementString("FileName", "" );//FileName	上传文件名	 ********
            xmlWriter.writeElementString("TXTDSP", "");//TXTDSP	摘要码       ********				
            xmlWriter.writeElementString("TRSUSE", p_req1988.useType);//TRSUSE	备注
            xmlWriter.writeElementString("Flag5", p_req1988.isPrivate);//Flag5	公转私检查标志		0-否，1-是 ********
            xmlWriter.writeElementString("AppMsg0", "");//AppMsg0	短信附言	
            xmlWriter.writeElementString("DWMC", getBankConfig().getSetValue("unitName", "", "1988"));//DWMC	单位名称				
            xmlWriter.writeElementString("DWBH", getBankConfig().getSetValue("unitNumber", "", "1988"));//DWBH	单位编号	
//            xmlWriter.writeElementString("DWMC", getBankConfig().getValueAsString("unitName"));//DWMC	单位名称				
//            xmlWriter.writeElementString("DWBH", getBankConfig().getValueAsString("unitNumber"));//DWBH	单位编号				
            xmlWriter.writeElementString("CrtlCode","004");//CrtlCode	业务编号	 代发-004；代扣-104；
            xmlWriter.writeStartElement("records");//records(多条转账操作)
//            int num=1;
            while(p_req1988.readRecord()){
            xmlWriter.writeStartElement("rd"); //rd(一条转账指令的明细)
//            String CustNo = String.format("%025d", num);

            xmlWriter.writeElementString("CustNo", p_req1988.readedDetail.askNumber);//CustNo	用户编号		********
			String paydate = getBankConfig().getValueAsString("testDate");
			if (paydate != null && paydate != "") {
				//yyyy-MM-dd
				p_req1988.readedDetail.payDate = paydate.substring(0,10);
				p_req1988.readedDetail.payTime = paydate.substring(paydate.length()-8,paydate.length());
			}
            xmlWriter.writeElementString("TranDate",Format.Date10Format.format(p_req1988.readedDetail.getPayDateTime()));//TranDate	数据日期		格式：YYYY-MM-DD
            xmlWriter.writeElementString("AcctNo", p_req1988.readedDetail.recAct);//AcctNo	帐号/卡号
            xmlWriter.writeElementString("CustName",p_req1988.readedDetail.recName);//CustName	用户姓名			可为空
            xmlWriter.writeElementString("TranAmt", p_req1988.readedDetail.payAmount);//TranAmt	代发金额			16,2
            xmlWriter.writeElementString("MemoCode","");//MemoCode	摘要码		主机摘要码
            xmlWriter.writeElementString("Remark",p_req1988.readedDetail.memo);//Remark	备注		可为空
//            num++;
			xmlWriter.writeEndElement();
            }


            xmlWriter.writeEndDocument();
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());// 发送银行
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                // 解析银行返回
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1],tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/root/head/RetCode");
                    String tmpRetMsg = tmpBkReader.getFirstText("/root/head/RetMsg").trim();;
                        retAts.respCode = "0";
                        retAts.transState = tmpRetCode;
                        retAts.respInfo = tmpRetMsg;
						if("999999".equals(tmpRetCode)){
							tmpRetCode = tmpRetCode + "+" + tmpRetMsg;
						}
						retAts.payInfoCode = tmpRetCode;
                        retAts.reqSeqID = tmpBkReader.getFirstText("/root/head/TxPackNo");

                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpSbMsg.toString();
                }
            } else if (tmpStrRet[0].equals(ConnState.FAIL)) {
                retAts.respCode = "0";
                retAts.respInfo = tmpStrRet[1];
                retAts.reqSeqID = p_req1988.reqBatchNO;
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = tmpStrRet[0];
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = tmpStrRet[1];
            }


		} catch (Exception ex) {
			// TODO: handle exception
			retAts.respCode = "-1";
            retAts.respInfo = ex.toString();
            ex.printStackTrace();
			WriteBankLogLn(ex);
		}
		 if ("-1".equals(retAts.respCode) && StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
             retAts.reqSeqID = p_req1988.reqBatchNO;
         }
         retAts.writeRetToATS();
         return retAts;
     }


	/* 批量代付状态查询*/
	@Override
	public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
		// TODO Auto-generated method stub

		RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_req1998.reqHeader);
		try {


			 bnkVersion = "0.0.0.1";
			 bank ="KLB";
			bnkOrgId=bankFront.corpNo;
			bnkoOrgName=bankFront.org;
			 bnkTxCode="3032";
			 bnkTxPackNo=getQryTransID();

			/*
			 *
			 *
			 *  写的xml有很多的问题
			 *
			 *
			 *  */

			 XmlTextWriter xmlWriter = new XmlTextWriter();
	         writeCommonHeader(xmlWriter);

	         xmlWriter.writeStartElement("body");
	         xmlWriter.writeElementString("PayAccNo", p_req1998.ownAct); // PayAccNo	发起方账号	*******
			String paydate = getBankConfig().getValueAsString("testDate");
			if (paydate != null && paydate != "") {
				p_req1998.bgnDate = paydate;
			}
	         xmlWriter.writeElementString("DueDate",Format.Date8Format.format(p_req1998.getBgnDateTime()));// DueDate	原前置交易日期
	         xmlWriter.writeElementString("TxPackNoQuery", p_req1998.reqBatchNO);// TxPackNoQuery	所要查询的指令包序列号
	         xmlWriter.writeElementString("DWBH", getBankConfig().getSetValue("unitNumber", "", "1988")); // DWBH	单位编号		*******
	         xmlWriter.writeElementString("CrtlCode", "004"); // CrtlCode	业务编号	 代发-004；代扣-104；

	         xmlWriter.writeEndElement();
             xmlWriter.writeEndDocument();
	         String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
             if (tmpStrRet[0].length() == 0) {
                 StringBuilder tmpSbMsg = new StringBuilder();

                 XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);

                 if (tmpBkReader != null) {
                     String tmpRetCode = tmpBkReader.getFirstText("/root/head/RetCode");
					 String tmpRetMsg = tmpBkReader.getFirstText("/root/head/RetMsg").trim();

					 String retTxPackNo = tmpBkReader.getFirstText("/root/head/TxPackNo");
						if(!bnkTxPackNo.equals(retTxPackNo)){
							retAts.respCode = "-1";
	                        retAts.respInfo = "银行响应的TxPackNo值"+retTxPackNo+"与请求值"+bnkTxPackNo+"不一致";
	                        retAts.writeAfterDetail();
	                        return retAts;
						}
						retAts.reqSeqID = p_req1998.reqBatchNO;
                             retAts.respCode = "0";
					 	String payinfocode = tmpRetCode;
							 if("999999".equals(tmpRetCode)){
								 payinfocode = tmpRetCode + "+" + tmpRetMsg;
							 }

							 if (tmpRetMsg.contains("没有记录") ){
								 if (!canBeNotExist(p_req1998, retAts, 60)) {
									 retAts.writeAfterDetail();
									 return retAts;
								 }
								 retAts.respCode = "0";
								 retAts.reqSeqID = p_req1998.reqBatchNO;
								 retAts.transState = tmpRetCode;
								 retAts.respInfo = tmpRetMsg;
								 retAts.payInfoCode = payinfocode;
								 retAts.writeAfterDetail();
								 return retAts;
							 }

								 retAts.transState = tmpRetCode;
								 retAts.respInfo = tmpRetMsg;
								 retAts.payInfoCode = payinfocode;

                             retAts.writeBeforeDetail();
                             while (tmpBkReader.read("/root/body/records/rd")) {
                                 RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();

                                 tmpRetDetail.recName = tmpBkReader.readedXElement.getSingleText("CustName");//收方户名
                                 tmpRetDetail.recAct = tmpBkReader.readedXElement.getSingleText("AcctNo");//收方账号
                                 tmpRetDetail.payAmount = tmpBkReader.readedXElement.getSingleText("PayAmt");//交易金额;

								 String resCode = tmpBkReader.readedXElement.getSingleText("BCode");
								 String resMsg = tmpBkReader.readedXElement.getSingleTextNotNull("BMessage").trim();;

								 tmpRetDetail.result = resCode;
								 if("999999".equals(resCode)){
									 resCode = resCode + "+" + resMsg;
								 }
								 tmpRetDetail.payInfoCode = resCode;
								 tmpRetDetail.memo = resMsg ;
							 	 tmpRetDetail.postScript = tmpBkReader.readedXElement.getSingleTextNotNull("CustNo");
                                 retAts.writeRetDetail(tmpRetDetail);
                             }


                 } else {
                     retAts.respCode = "-1";
                     retAts.respInfo = tmpSbMsg.toString();
                 }
             } else {
                 retAts.respCode = "-1";
                 retAts.respInfo = tmpStrRet[1];
             }

		} catch (Exception ex) {
			// TODO: handle exception
			retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            ex.printStackTrace();
			WriteBankLogLn(ex);
		}
		if (retAts.respCode.equals("-1")
                && StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
			retAts.reqSeqID = p_req1998.reqBatchNO;
        }
        if (retAts.respCode.equals("-1")) {
            retAts.writeBeforeDetail();
        }
        retAts.writeAfterDetail();
        return retAts;

	}


	/* 批量代收（代扣）提交*/
	@Override
	public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
		// TODO Auto-generated method stub

		 RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_req9188.reqHeader);
		 try {

				bnkVersion = "0.0.0.1";
	        	bank ="KLB";
			 	bnkOrgId=bankFront.corpNo;
				bnkoOrgName=bankFront.org;
	        	bnkTxCode="3030";
	        	bnkTxPackNo=p_req9188.reqBatchNO;
	        	 XmlTextWriter xmlWriter = new XmlTextWriter();

	             writeCommonHeader(xmlWriter);

	             xmlWriter.writeStartElement("body");
	             xmlWriter.writeElementString("PayAccNo", p_req9188.ownAct);//PayAccNo	发起方账号
	             xmlWriter.writeElementString("TotalNum", p_req9188.totalNum);//TotalNum	交易笔数				为1，默认1
	             xmlWriter.writeElementString("CurrType", "01");//CurrType	币种			01-人民币
	             xmlWriter.writeElementString("TotalAmt", p_req9188.totalAmt);//TotalAmt	汇总代发金额
	             xmlWriter.writeElementString("TrnFlag", "8");//TrnFlag	处理标志			代发-7；代扣-8；
	             xmlWriter.writeElementString("FileName", "" );//FileName	上传文件名
	             xmlWriter.writeElementString("TXTDSP", "");//TXTDSP	摘要码       ********
	             xmlWriter.writeElementString("TRSUSE", p_req9188.useType);//TRSUSE	备注
	             xmlWriter.writeElementString("Flag5", p_req9188.isPrivate);//Flag5	公转私检查标志		0-否，1-是 ********
	             xmlWriter.writeElementString("AppMsg0", "");//AppMsg0	短信附言		 ********
	             xmlWriter.writeElementString("DWMC", getBankConfig().getSetValue("unitName", "", "9188"));//DWMC	单位名称
	             xmlWriter.writeElementString("DWBH", getBankConfig().getSetValue("unitNumber", "", "9188"));//DWBH	单位编号
//	             xmlWriter.writeElementString("DWMC", getBankConfig().getValueAsString("unitName"));//DWMC	单位名称		********
//	             xmlWriter.writeElementString("DWBH", getBankConfig().getValueAsString("unitNumber"));//DWBH	单位编号		********
	             xmlWriter.writeElementString("CrtlCode","104");//CrtlCode	业务编号	 代发-004；代扣-104；
	             xmlWriter.writeStartElement("records");//records(多条转账操作)
	             int num=1;
	             while(p_req9188.readRecord()){

	             xmlWriter.writeStartElement("rd"); //rd(一条转账指令的明细)
	             String CustNo = String.format("%025d", num);
	             xmlWriter.writeElementString("CustNo", p_req9188.readedDetail.askNumber);//CustNo	用户编号
					 String paydate = getBankConfig().getValueAsString("testDate");
					 if (paydate != null && paydate != "") {
						 //yyyy-MM-dd
						 p_req9188.readedDetail.payDate = paydate.substring(0,10);
						 p_req9188.readedDetail.payTime = paydate.substring(paydate.length()-8,paydate.length());
					 }
	             xmlWriter.writeElementString("TranDate", Format.Date10Format.format(p_req9188.readedDetail.getPayDateTime()));//TranDate	数据日期		格式：YYYY-MM-DD
	             xmlWriter.writeElementString("AcctNo", p_req9188.readedDetail.payAct);//AcctNo	帐号/卡号
	             xmlWriter.writeElementString("CustName", p_req9188.readedDetail.payName);//CustName	用户姓名			可为空
	             xmlWriter.writeElementString("TranAmt", p_req9188.readedDetail.payAmount);//TranAmt	代发金额			16,2
	             xmlWriter.writeElementString("MemoCode","");//MemoCode	摘要码		主机摘要码
	             xmlWriter.writeElementString("Remark",p_req9188.readedDetail.memo);//Remark	备注		可为空
	             num++;
	             xmlWriter.writeEndElement();
	             }
	                xmlWriter.writeEndDocument();
	             String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
	             if (tmpStrRet[0].length() == 0) {
	                 StringBuilder tmpSbMsg = new StringBuilder();
	                 XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);

	                 if (tmpBkReader != null) {
	                     String tmpRetCode = tmpBkReader.getFirstText("/root/head/RetCode");
						 String tmpRetMsg = tmpBkReader.getFirstText("/root/head/RetMsg").trim();;

							 retAts.transState = tmpRetCode;
							 retAts.respInfo = tmpRetMsg;
							 if("999999".equals(tmpRetCode)){
								 tmpRetCode = tmpRetCode + "+" + tmpRetMsg;
							 }
							 retAts.payInfoCode = tmpRetCode;
	                         String reqSeqID = tmpBkReader.getFirstText("/root/head/TxPackNo");
	                         if (StringHelper.hasAnyChar(reqSeqID)) {
	                             retAts.reqSeqID = reqSeqID;
	                         } else {
	                             retAts.reqSeqID = p_req9188.reqBatchNO;
	                         }

	                 } else {
	                     retAts.respCode = "-1";
	                     retAts.respInfo = tmpSbMsg.toString();
	                 }
	             } else if (tmpStrRet[0].equals(ConnState.FAIL)) {
	                 retAts.respCode = "0";
	                 retAts.respInfo = tmpStrRet[1];
	                 retAts.reqSeqID = p_req9188.reqBatchNO;
	                 retAts.transState = PaymentState.FAIL_Batch;
	                 retAts.payInfoCode = tmpStrRet[0];
	             } else {
	                 retAts.respCode = "-1";
	                 retAts.respInfo = tmpStrRet[1];
	             }


		} catch (Exception ex) {
			// TODO: handle exception
			 ex.printStackTrace();

	         retAts.respCode = "-1";
	         retAts.respInfo = ex.toString();
			WriteBankLogLn(ex);
		}
		 if ("-1".equals(retAts.respCode) && StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
            retAts.reqSeqID = p_req9188.reqBatchNO;
        }

        retAts.writeRetToATS();
        return retAts;
	}



	/* 批量代收（代扣）状态查询 */
	@Override
	public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
		// TODO Auto-generated method stub
		RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_req9198.reqHeader);
		try {

			bnkVersion = "0.0.0.1";
			bank = "KLB";
			bnkOrgId=bankFront.corpNo;
			bnkoOrgName=bankFront.org;
			bnkTxCode = "3032";
			bnkTxPackNo = getQryTransID();

			XmlTextWriter xmlWriter = new XmlTextWriter();
			writeCommonHeader(xmlWriter);

			xmlWriter.writeStartElement("body");
			xmlWriter.writeElementString("PayAccNo", p_req9198.ownAct); // PayAccNo
																					// 发起方账号
																					// *******
			String paydate = getBankConfig().getValueAsString("testDate");
			if (paydate != null && paydate != "") {
				p_req9198.bgnDate = paydate;
			}
			xmlWriter.writeElementString("DueDate", Format.Date8Format.format(p_req9198.getBgnDateTime()));// DueDate原前置交易日期
			xmlWriter.writeElementString("TxPackNoQuery", p_req9198.reqBatchNO);// TxPackNoQuery所要查询的指令包序列号
			xmlWriter.writeElementString("DWBH", getBankConfig().getSetValue("unitNumber", "", "9188")); // DWBH 单位编号 *******
			xmlWriter.writeElementString("CrtlCode", "104"); // CrtlCode 业务编号
																// 代发-004；代扣-104；
			xmlWriter.writeEndElement();
			xmlWriter.writeEndDocument();
			String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
			if (tmpStrRet[0].length() == 0) {
				StringBuilder tmpSbMsg = new StringBuilder();
				XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);

				if (tmpBkReader != null) {
					String tmpRetCode = tmpBkReader.getFirstText("/root/head/RetCode");
					String tmpRetMsg = tmpBkReader.getFirstText("/root/head/RetMsg").trim();
					String retTxPackNo = tmpBkReader.getFirstText("/root/head/TxPackNo");
					if(!bnkTxPackNo.equals(retTxPackNo)){
						retAts.respCode = "-1";
                        retAts.respInfo = "银行响应的TxPackNo值"+retTxPackNo+"与请求值"+bnkTxPackNo+"不一致";
                        retAts.writeAfterDetail();
                        return retAts;
					}
					retAts.reqSeqID = p_req9198.reqBatchNO;
					retAts.respCode = "0";
					String payinfocode = tmpRetCode;
					if("999999".equals(tmpRetCode)){
						payinfocode = tmpRetCode + "+" + tmpRetMsg;
					}

                    if (tmpRetMsg.contains("没有记录") ){
                        if (!canBeNotExist(p_req9198, retAts, 60)) {
                            retAts.writeAfterDetail();
                            return retAts;
                        }
                        retAts.respCode = "0";
                        retAts.reqSeqID = p_req9198.reqBatchNO;
                        retAts.transState = tmpRetCode;
                        retAts.respInfo = tmpRetMsg;
                        retAts.payInfoCode = payinfocode;
                        retAts.writeAfterDetail();
                        return retAts;
                    }

					retAts.transState = tmpRetCode;
					retAts.respInfo = tmpRetMsg;
					retAts.payInfoCode = payinfocode;

					if (StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
						retAts.reqSeqID = p_req9198.reqBatchNO;
					}

					retAts.writeBeforeDetail();
					while (tmpBkReader.read("/root/body/records/rd")) {
						RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();

						tmpRetDetail.payName = tmpBkReader.readedXElement.getSingleText("CustName");//
						tmpRetDetail.payAct = tmpBkReader.readedXElement.getSingleText("AcctNo");//
						tmpRetDetail.payAmount = StringHelper
								.amountDivide100(tmpBkReader.readedXElement.getSingleText("TranAmt"));//

						tmpRetDetail.curType = convertCurToATS(tmpBkReader.readedXElement.getSingleText("CurrType"));// 币种

						String resCode = tmpBkReader.readedXElement.getSingleText("BCode");
						String resMsg = tmpBkReader.readedXElement.getSingleTextNotNull("BMessage").trim();

						tmpRetDetail.result = resCode;
						if("999999".equals(resCode)){
							resCode = resCode + "+" + resMsg;
						}
						tmpRetDetail.payInfoCode = resCode;
						tmpRetDetail.memo = resMsg ;
						tmpRetDetail.postScript = tmpBkReader.readedXElement.getSingleTextNotNull("CustNo");

						retAts.writeRetDetail(tmpRetDetail);
					}

				} else {
					retAts.respCode = "-1";
					retAts.respInfo = tmpSbMsg.toString();
				}
			} else {
				retAts.respCode = "-1";
				retAts.respInfo = tmpStrRet[1];
			}
		} catch (Exception ex) {
			// TODO: handle exception
			ex.printStackTrace();

			retAts.respCode = "-1";
			retAts.respInfo = ex.getMessage();

			WriteBankLogLn(ex);
		}

		if ("-1".equals(retAts.respCode) && StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
			retAts.reqSeqID = p_req9198.reqBatchNO;
		}

		if ("-1".equals(retAts.respCode)) {
			retAts.writeBeforeDetail();
		}

		retAts.writeAfterDetail();
		return retAts;
	}

}
